package com.singing.manager;

import com.singing.dao.SingerDao;
import com.singing.model.Command;
import com.singing.model.Singer;

import java.util.List;
import java.util.Scanner;

public class SingerUpdateManager extends BaseManager {

    private static final int REFRESH_PAGE = 1;
    // 删除歌手
    private static final int UPDATE_SINGER = 2;

    SingerDao singerDao = new SingerDao();

    public SingerUpdateManager(String title, List<Command> commandList) {
        super(title, commandList);
    }

    @Override
    protected int processCommand(int command) {
        switch (command) {
            case REFRESH_PAGE:
                break;
            case UPDATE_SINGER:
                updateSinger();
                break;
        }
        return command;
    }

    private void updateSinger() {
        Scanner scanner = new Scanner(System.in);
        Integer id = null;
        // 更新歌手信息
        while (true) {
            System.out.println("请输入歌手id");
            String idStr = scanner.next();

            // 判断是否是数字
            try {
                id = Integer.parseInt(idStr);
                break;
            } catch (NumberFormatException e) {
                e.printStackTrace();
                System.out.println("歌手id输入有误，请重新输入");
            }
        }

        System.out.println("请输入歌手名称");
        String name = scanner.next();

        Integer gender = null;
        while (true) {
            System.out.println("歌手性别(0-男，1-女)：");
            String genderStr = scanner.next();
            gender = null;
            try {
                gender = Integer.parseInt(genderStr);

                // 判断性别是否合法
                if (gender != 0 && gender != 1) {
                    throw new NumberFormatException();
                }

                break;

            } catch (NumberFormatException e) {
                e.printStackTrace();
                System.out.println("歌手性别输入错误，请重新输入");
            }
        }

        Singer singer = new Singer(id, name, gender);

        int result = singerDao.update(singer);

        if (result == 1) {
            System.out.println("更新成功");
        } else {
            System.err.println("更新失败");
        }


    }

    @Override
    protected void printTitleExtra() {
        System.out.println("歌手id\t\t歌手名称\t\t歌手性别");
        showSingerList();
    }

    private void showSingerList() {
        List<Singer> singers = singerDao.selectAll();
        Scanner scanner = new Scanner(System.in);
        for (Singer singer : singers) {
            System.out.println(singer.getId() + "\t\t" + singer.getName() + "\t\t" + (singer.getGender() == 0 ? "男" : "女"));
        }
    }
}
